import {
  EditableProTable,
  ProTable,
  ProFormDigit, ProFormMoney, ProFormCheckbox, ProFormText
} from '@ant-design/pro-components';
import React, { useEffect, useState, forwardRef } from 'react';
import { Button, Modal, Upload, Space, Tooltip, message } from "antd";
import Decimal from 'decimal.js';
import TheButton from "@/components/TheButton/index.jsx";
import TheImage from "@/components/TheImage/index.jsx";
import './style.less'
import { apiGoodsStockInfo } from '@/api/marketingTool';
import { apiPostSpellTogetherEditDelGoods, apiGetPlatformSet } from '@/api/spellTogether/index.js';
import { apiGetStoreInfo } from "@/api/couponManagement/couponsList.js";
import log from "eslint-plugin-react/lib/util/log.js";


const { confirm } = Modal
const Editable = (props) => {
  const selectKeys = props.value.map((item) => item.goodsId);
  const [dataSource, setDataSource] = useState(props.value || []);
  const [selectedRows, setSelectedRows] = useState([]);
  const [sortHide, setSortHide] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [pageParams, setPageParams] = useState({
    pageNo: 1,
    pageSize: 10,
    // total: 0
  })
  const mode = props.mode;
  const activityId = props.activityId;
  useEffect(() => {
    apiGetStoreInfo().then(res => {
      if (res.code === 0) {
        if (res.data.isProprietary === 'N') {
          apiGetPlatformSet().then(v => {
            if (v.code === 0) {
              if (!v.data) {
                setSortHide(true)
              }
            }
          })
        }
      }
    })
    if (mode === 'edit') {
      // 处理编辑时回显数据赋值给弹窗默认数据
      setSelectedRows(props.value)
    }
  }, [])
  const columns = [
    {
      title: '商品ID',
      dataIndex: 'goodsId',
      key: 'goodsId',
      width: 200,
      ellipsis: true
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      key: 'goodsName',
      width: 300,
      ellipsis: true,
    },
    {
      title: 'sku',
      dataIndex: 'sku',
      key: 'sku',
      width: 300,
      ellipsis: true,
      render: (text, record, index) => (
        record.skuInfoVos.map((sku, skuIndex) => {
          const strArr = sku.skuAttributes.map(item => item.goodsKeyName + ':' + item.goodsValue)
          return <div className='span' key={skuIndex + 'sku'}>{strArr.join(';')}</div>
        })
      )
    },
    {
      title: '库存',
      dataIndex: 'skuStock',
      key: 'skuStock',
      width: 100,
      render: (text, record, index) => (
        record.skuInfoVos.map((sku, skuIndex) => {
          return <div className='span'
            key={skuIndex + 'skuStock'}>{sku.skuStock === -1 ? '不限量' : sku.skuStock}</div>
        })
      )
    },
    {
      title: '活动库存',
      dataIndex: 'a_stock',
      key: 'a_stock',
      width: 150,
      render: (text, record, index) => (
        record.skuInfoVos.map((sku, skuIndex) => {
          return (
            <div className='span' key={skuIndex + 'a_stock'}>
              <ProFormDigit
                // name={['temp', `${index}-${skuIndex}-a_stock`]}
                name={['temp', record.goodsId, 'skuInfoVos', skuIndex, `a_stock`]}
                min={0}
                max={999999}
                readonly={mode === 'view' || sku.isJoin}
                fieldProps={{
                  precision: 0,
                  // value: sku.a_stock,
                  onChange: async (e) => {
                    await aInputChange(e, 'a_stock', index, skuIndex);
                  }
                }}
                initialValue={sku.a_stock}
                formItemProps={{
                  style: {
                    marginBottom: 0
                  },
                }}
                rules={[
                  {
                    required: true,
                    message: '请填写活动库存'
                  },
                  {
                    validator: (_, value) => {
                      if (value > sku.skuStock && sku.skuStock !== -1) {
                        return Promise.reject(new Error('活动库存必须小于等于实际库存值'));
                      }
                      if (sku.hasOwnProperty('goodsSurplusSum') || sku.hasOwnProperty('goodsBuySum')) {
                        if (value < sku.goodsBuySum) {
                          return Promise.reject(new Error('活动库存小于实际已售卖的数量'));
                        }
                      }
                      return Promise.resolve();
                    }
                  }
                ]}
              />
            </div>
          )
        })
      )
    },
    {
      title: '日常价',
      dataIndex: 'skuCurrentPrice',
      key: 'skuCurrentPrice',
      width: 150,
      render: (text, record) => (
        record.skuInfoVos.map((sku, skuIndex) => {
          return (
            <div className='span' key={skuIndex + 'skuCurrentPrice'}>
              <ProFormMoney
                readonly={true}
                formItemProps={{
                  style: {
                    marginBottom: 0
                  }
                }}
                value={Decimal(sku.skuCurrentPrice).div(Decimal(100)).toFixed(2) || 0}
              />
            </div>
          )
        })
      )
    },
    {
      title: '拼团价',
      dataIndex: 'a_price',
      key: 'a_price',
      width: 150,
      render: (text, record, index) => (
        record.skuInfoVos.map((sku, skuIndex) => {
          return (
            <div className='span' key={skuIndex + 'a_price'}>
              <ProFormMoney
                // name={['temp', `${index}-${skuIndex}-a_price`]}
                name={['temp', record.goodsId, 'skuInfoVos', skuIndex, `a_price`]}
                min={0}
                max={999999}
                readonly={mode === 'view' || sku.isJoin}
                formItemProps={{
                  style: {
                    marginBottom: 0
                  }
                }}
                initialValue={sku.a_price}
                onChange={async (e) => {
                  await aInputChange(e, 'a_price', index, skuIndex);
                }}
                rules={[
                  {
                    required: true,
                    message: '请填写拼团价'
                  },
                  {
                    validator: (_, value) => {
                      if (value === 0) {
                        return Promise.reject(new Error('请填写拼团价'));
                      }
                      if (value * 100 > sku.skuCurrentPrice) {
                        return Promise.reject(new Error('拼团价必须小于等于日常价'));
                      }
                      return Promise.resolve();
                    }
                  }
                ]}
              />
            </div>
          )
        })
      )
    },
    {
      title: '排序',
      dataIndex: 'killSort',
      key: 'killSort',
      width: 150,
      hideInTable: sortHide,
      render: (text, record, index) => (
        <div key={index + 'killSort'} className='span'>
          <ProFormDigit
            // name={['temp', `${index}-killSort`]}
            name={['temp', record.goodsId, 'killSort']}
            min={0}
            max={999999}
            readonly={mode === 'view'}
            fieldProps={{
              precision: 0,
            }}
            formItemProps={{
              style: {
                marginBottom: 0
              }
            }}
            initialValue={record.killSort}
            onChange={async (e) => {
              await aInputChange(e, 'killSort', index);
            }}
            rules={[
              {
                required: true,
                message: '请填写排序'
              },
            ]}
          />
        </div>
      )
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: "right",
      hideInTable: mode === 'view',
      render: (text, record, index, action) => (
        <TheButton onClick={() => delGoods(record, index)}>删除</TheButton>
      )
    },
  ];
  const goodsColumns = [
    {
      title: "商品ID",
      key: "goodsId",
      width: 100,
      dataIndex: "goodsId",
    },
    {
      title: "商品名称",
      key: "goodsName",
      width: 300,
      dataIndex: "goodsName",
      ellipsis: true,
    },
    {
      title: "商品图片",
      key: "goodsShowImages",
      dataIndex: "goodsShowImages",
      hideInSearch: true,
      width: 500,
      render: (text) => {
        return <TheImage
          width={80}
          height={80}
          src={text.split(',')}
        />
      }
    },
    {
      title: "所属类目",
      key: "goodsClassifyName",
      dataIndex: "goodsClassifyName",
      hideInSearch: true,
    },
    {
      title: "商品状态",
      key: "goodsStatus",
      dataIndex: "goodsStatus",
      width: 100,
      hideInSearch: true,
      render: (text, render) => {
        return text === 'Y' ? '上架' : '下架'
      },
    },
    {
      title: "上次操作时间",
      key: "updateTime",
      dataIndex: "updateTime",
      hideInSearch: true,
    }
  ]
  const aInputChange = (e, key, index, skuIndex) => {
    const data = [...dataSource]
    const { pageNo, pageSize } = pageParams
    const currentIndex = (pageNo - 1) * pageSize + index
    if (key === 'killSort') {
      data[currentIndex][key] = e
    } else {
      data[currentIndex].skuInfoVos[skuIndex][key] = e
    }
    setDataSource(data)
  }
  const delGoods = (record, index) => {
    if (mode === "add") {
      confirm({
        title: "提示",
        type: 'warning',
        content: "是否删除该商品？",
        onOk: async () => {
          const data = [...dataSource]
          const { pageNo, pageSize } = pageParams
          data.splice((pageNo - 1) * pageSize + index, 1)
          setSelectedRows(data)
          setDataSource(data)
        }
      });
    }
    else {
      apiPostSpellTogetherEditDelGoods({ activityId, goodsId: record.goodsId }).then(res => {
        if (res.code === 0) {
          if (res.data === 1) {
            Modal.warning({
              title: '提示',
              content: '该商品已有拼团任务，不可删除！',
            });
          } else {
            confirm({
              title: "提示",
              type: 'warning',
              content: "删除商品可能导致正在购买的消费者无法正常下单，是否继续删除？",
              onOk: async () => {
                const data = [...dataSource]
                const { pageNo, pageSize } = pageParams
                data.splice((pageNo - 1) * pageSize + index, 1)
                setSelectedRows(data)
                setDataSource(data)
              }
            });
          }
        }
      })
    }
  }

  useEffect(() => {
    props.set(dataSource)
  }, [dataSource])

  let tableProps = {}
  if (mode === 'view') {
    tableProps = {
      toolBarRender: false
    }
  }
  else {
    tableProps = {
      toolBarRender: (action) => {
        return action.toolBarRender
      }
    }
  }
  return <>
    <ProTable
      {...tableProps}
      className='noCanJoinGood'
      readonly={true}
      rowKey={(record) => record.goodsId}
      search={false}
      options={false}
      bordered={true}
      cardBordered={mode !== 'view'}
      scroll={{ y: '500px' }}
      headerTitle={
        <Space>
          <TheButton
            key="save"
            onClick={() => {
              setModalOpen(true)
            }}
          >
            选择商品
          </TheButton>
        </Space>
      }
      columns={columns}
      dataSource={dataSource}
      pagination={{
        current: pageParams.pageNo,
        pageSize: pageParams.pageSize,
        onChange: (page, pageSize) => setPageParams({
          pageNo: page,
          pageSize: pageSize
        }),
      }}
    />
    <Modal
      title={'选择商品'}
      width={'80%'}
      open={modalOpen}
      destroyOnClose={true}
      onOk={() => {
        // 处理已选择商品再次勾选/不勾选，已设置值是否清空问题
        if (dataSource.length) {
          let oldData = dataSource.map(item => item.goodsId);
          let newData = selectedRows.map(item => item.goodsId);
          let saveIds = oldData.filter(item => newData.includes(item));
          selectedRows.map(item => {
            if (saveIds.includes(item.goodsId)) {
              const data = props.formRef.current.getFieldValue(['temp', item.goodsId])
              let skuInfoVos = []
              item.skuInfoVos.forEach((v, i) => {
                if (data && data.skuInfoVos) {
                  skuInfoVos.push({ ...v, ...data.skuInfoVos[i] })
                } else {
                  skuInfoVos.push({ ...v })
                }
              })
              item.skuInfoVos = skuInfoVos;
              item.killSort = data ? data.killSort : null;
              return item
            }
          })
          let ids = oldData.filter(item => !newData.includes(item))
          ids.forEach(item => {
            props.formRef.current.resetFields([['temp', item]]);
          })
        }
        // 设置表单表格数据
        setDataSource(selectedRows)
        setModalOpen(false)
      }}
      onCancel={() => setModalOpen(false)}
    >
      <ProTable
        bordered={true}
        options={false}
        scroll={{ x: 960, y: '57vh' }}
        rowKey={(record) => record.goodsId}
        columns={goodsColumns}
        params={{
          storeStatus: 'Y',
          goodsStatus: 'Y',
          reviewStatus: 'T'
        }}
        request={async (params, sort, filter) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const res = await apiGoodsStockInfo({
            pageNo: params.current,
            pageSize: params.pageSize,
            ...params
          });
          return {
            data: res.data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: res.code === 0,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: res.totalCount,
          };
        }}
        pagination={{
          defaultPageSize: 10
        }}
        rowSelection={{
          defaultSelectedRowKeys: selectKeys,
          preserveSelectedRowKeys: true,
          onChange: (keys, rows) => {
            setSelectedRows((prev) => {
              let arr = []
              // 处理跨页勾选值问题
              rows.forEach((item, index) => {
                if (item === undefined) {
                  arr.push(prev.find(v => v.goodsId === keys[index]))
                }
                else {
                  arr.push(item)
                }
              })
              return arr;
            });
          }
        }}
        search={{
          optionRender: (searchConfig, formProps, dom) => {
            return dom.reverse()
          }
        }}
      />
    </Modal>
  </>
}
export default Editable;
